﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using CLEX.AdminUI.Service;

namespace CLEX.AdminUI.ViewModel
{
    internal sealed class FriendRequestEditVM : ViewModelBase
    {
        private readonly Facade facade;
        private RelayCommand ok;
        private RelayCommand cancel;
        private RelayCommand apply;
        private FriendRequestData friendRequest;
        private readonly List<UserReadVM> users;

        public ICommand OK
        {
            get
            {
                if (ok == null)
                {
                    ok = new RelayCommand(DoOK);
                }
                return ok;
            }
        }

        public ICommand Cancel
        {
            get
            {
                if (cancel == null)
                {
                    cancel = new RelayCommand(DoCancel);
                }
                return cancel;
            }
        }

        public ICommand Apply
        {
            get
            {
                if (apply == null)
                {
                    apply = new RelayCommand(DoApply);
                }
                return apply;
            }
        }

        public int FromUserId
        {
            get { return friendRequest.FromUserId; }
        }

        public int ToUserId
        {
            get { return friendRequest.ToUserId; }
        }

        public IEnumerable<UserReadVM> Users
        {
            get { return users; }
        } 

        public FriendRequestEditVM(Facade facade, FriendRequestData friendRequest)
        {
            this.facade = facade;
            this.friendRequest = friendRequest;
            this.users = facade.GetAllUsers().Select(p => new UserReadVM(p)).ToList();
        }

        private void DoOK()
        {
            try
            {
                facade.UpdateFriendRequest(friendRequest);
            }
            catch (Exception ex)
            {
                facade.ShowError("An unexpected error occured while updating the friend request.", ex);
                return;
            }
            FireCloseRequested();
        }

        private void DoCancel()
        {
            FireCloseRequested();
        }

        private void DoApply()
        {
            try
            {
                facade.UpdateFriendRequest(friendRequest);
            }
            catch (Exception ex)
            {
                facade.ShowError("An unexpected error occured while updating the friend request.", ex);
                return;
            }
        }
    }
}
